# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import base64
import errno
import logging
import os
import random
import shutil
import string
import time
from StringIO import StringIO

import psycopg2

import openerp
from openerp import netsvc
from openerp import pooler
from openerp import tools
from openerp.osv import fields, osv
from openerp.osv.orm import except_orm
from openerp.tools.misc import ustr
from openerp.tools.translate import _
from openerp.tools.safe_eval import safe_eval

from content_index import cntIndex

_logger = logging.getLogger(__name__)
class portal_byf(osv.osv):
    _name = "portal.byf"
    _description = "Portal Byf"  
    
      
    _columns = {
        'name': fields.char('Name', size=64),
        'state': fields.selection([
            ('draft', 'Draft'),
            ('process', 'Process'),
            ('done', 'Done'),
            ], 'Status'),
        'date' : fields.datetime("Date"),
        'user_id': fields.many2one('res.users', 'Responsible'), 
                  
        'create_date':fields.date("Creation Date"),
        'write_date':fields.date("Update Date"),
        'closed_date':fields.date("Closed"),        
        'partner_id': fields.many2one('res.partner', 'Customer', required=True),        
        'document_type_id': fields.many2one('document.type', 'Type'),  
        'note': fields.text('Note'),        
    }    

    _defaults = {
        'state': 'draft',
        'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),        
    }    
 
    def button_process(self, cr, uid, ids, context=None):                                               
        self.write(cr, uid, ids, {'state': 'process'}, context=context)
        return True    

    def button_done(self, cr, uid, ids, context=None):                                       
        self.write(cr, uid, ids, {'state': 'done'}, context=context)
        return True 
    
    def action_load_document_type(self, cr, uid, ids, context={}):
        if context is None:
            context = {}
        ir_model_data = self.pool.get('ir.model.data')
        form_res = ir_model_data.get_object_reference(cr, uid, 'init_portal_byf', 'load_document_type_form_view')
        form_id = form_res and form_res[1] or False
        return {
            'name': 'Load Document Type',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'load.document.type',
            'context': {},
#           'context': {'company_id': obj.company_id.id, 'bulk_ids': ids},
            'target' : 'new',
            'type': 'ir.actions.act_window',
        }
        return True   
    
    def action_view_document(self, cr, uid, ids, context=None):

        mod_obj = self.pool.get('ir.model.data')
        act_obj = self.pool.get('ir.actions.act_window')

        result = mod_obj.get_object_reference(cr, uid, 'init_portal_byf', 'action_document_order_view_tree')
        id = result and result[1] or False
        result = act_obj.read(cr, uid, [id], context=context)[0]
        document_ids = self.pool.get('document.order').search(cr, uid, [('portal_byf_id','=',ids[0])])
        if len(document_ids) > 1:
            result['domain'] = "[('id','in',["+','.join(map(str, document_ids))+"])]"    
        else:
            res = mod_obj.get_object_reference(cr, uid, 'init_portal_byf', 'document_order_view_tree')
            result['views'] = [(res and res[1] or False, 'tree')]
            result['res_id'] = document_ids and document_ids[0] or False
        return result                 
        
        
        
#         id = result and result[1] or False
#         result = act_obj.read(cr, uid, [id], context=context)[0]
#         #compute the number of delivery orders to display
#         pick_ids = []
#         for so in self.browse(cr, uid, ids, context=context):
#             pick_ids += [picking.id for picking in so.picking_ids]
#         #choose the view_mode accordingly
#         if len(pick_ids) > 1:
#             result['domain'] = "[('id','in',["+','.join(map(str, pick_ids))+"])]"
#         else:
#             res = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_out_form')
#             result['views'] = [(res and res[1] or False, 'form')]
#             result['res_id'] = pick_ids and pick_ids[0] or False
#         return result     

portal_byf()





